<template>
    <div class="init-container"> <!-- <h1>初始化</h1> -->
        <div class="finish-title">
            <el-steps :active="active" finish-status="success">
                <el-step title="全宗"></el-step>
                <el-step title="档案门类"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
        </div>
        <div class="init-main ">
            <div v-show="active == 0">
                <el-row :gutter="10" class="mb8" ref="refbut">
                    <!-- v-hasPermi="['system:user:add']" -->
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">添加</el-button>
                    </el-col>
                </el-row>
                <div class="main-iscrll">
                    <el-table v-loading="loading" :data="generalList" border class="margin-top-table">
                        <!-- <el-table-column type="selection" width="50" align="center" /> -->
                        <el-table-column label="序号" sortable align="center" type="index" />
                        <el-table-column label="全宗名称" align="center" key="fondsName" prop="fondsName"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="全宗号" align="center" key="fondsCode" prop="fondsCode"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope" v-if="scope.row.userId !== 1">
                                <el-button type="text" icon="el-icon-edit"
                                    @click="handleUpdate(scope.row)">修改</el-button>
                                <el-button type="text" icon="el-icon-delete"
                                    @click="handleDelete(scope.row)">删除</el-button>
                                <!-- v-hasPermi="['system:user:edit']" -->
                                <!--   v-hasPermi="['system:user:remove']" -->

                            </template>
                        </el-table-column>
                    </el-table>

                    <el-pagination class="el-page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="generalQueryParams.pageNum" :page-sizes="[10, 20, 50, 100]"
                        :page-size="generalQueryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
                        :total="generalTotal" background>
                    </el-pagination>
                </div>

            </div>
            <div v-show="active == 1">
                <el-row :gutter="10" class="mb8" ref="refbut">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" @click="addCatemodelTap">添加门类</el-button>
                    </el-col>
                </el-row>
                <div class="main-iscrll">
                    <el-table v-loading="loading" :data="generalList" border class="margin-top-table"
                        @selection-change="selectionChange" ref="multipleTable" :row-key="getRowKeys"
                        :expand-row-keys="expands" :row-class-name="getRowClass">
                        <el-table-column type="selection" width="50" align="center" />
                        <el-table-column label="序号" sortable align="center" type="index" />

                        <el-table-column type="expand">
                            <template slot-scope="props">
                                <el-table :data="props.row.children1111" style="width:89%;margin-left:9%" border>
                                    <el-table-column prop="label" label="门类名称">
                                    </el-table-column>
                                    <el-table-column prop="type" label="门类类型">
                                        <template slot-scope="propschild">
                                            <span v-if="propschild.row.type == '0'">组件类型</span>
                                            <span v-if="propschild.row.type == '1'">组卷类型</span>
                                            <span v-if="propschild.row.type == '3'">项目类型</span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </template>
                        </el-table-column>
                        <el-table-column label="全宗名称" align="center" prop="fondsName" :show-overflow-tooltip="true" />
                        <el-table-column label="全宗号" align="center" prop="fondsCode" :show-overflow-tooltip="true" />

                    </el-table>
                    <el-pagination class="el-page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="generalQueryParams.pageNum" :page-sizes="[10, 20, 50, 100]"
                        :page-size="generalQueryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
                        :total="generalTotal" background>
                    </el-pagination>

                </div>
            </div>
            <div v-show="active == 2">
                <div>
                    <i style="font-size:140px;margin: 30% auto 0;text-align: center;display: block;color: #13ce66"
                        class="el-icon-success"></i>
                    <p style="font-size: 21px;font-weight: bold;text-align: center;color: #13ce66">提交成功</p>
                </div>
            </div>
        </div>
        <div class="el-button-xyb">
            <el-button @click="nextTap" size="medium" v-show="isbutton">上一步</el-button>
            <el-button @click="prevTap" type="primary" size="medium">下一步</el-button>
        </div>

        <!-- 添加或修改用户配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="35%" style="margin-top:8%" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">

                <el-form-item label="全宗名称：" prop="fondsName">
                    <el-input v-model="form.fondsName" placeholder="请输入全宗名称" />
                </el-form-item>

                <el-form-item label="全宗号：" prop="fondsCode">
                    <el-input v-model="form.fondsCode" placeholder="请输入全宗号" onKeyUp="value=value.replace(/[\W]/g,'')"
                        @blur="salaryChange" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加全宗门类模板对话框 -->
        <el-dialog :title="catemodelTitle" :visible.sync="openCatemodel" width="35%" style="margin-top:8%"
            append-to-body>
            <el-tree :data="catemodelList" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current
                :props="defaultProps">
            </el-tree>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="getCheckedNodes">确 定</el-button>
                <el-button @click="getCheckedNodesCancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { addFONDS, updateFONDS, getFONDS, delFONDS, getcatemodeltreehadgroup } from "@/api/manage/general"
import { mdataGroup, listFONDS } from "@/api/initialization.js"
export default {
    data() {
        return {
            ids: undefined,
            isbutton: false,
            single: undefined,
            multiple: undefined,
            // 是否显示弹出层
            open: false,
            //添加门类是否弹出ceng
            openCatemodel: false,
            // 弹出层标题
            title: "",
            catemodelTitle: "",
            active: 0,
            generalList: undefined,
            catemodelList: undefined,
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            generalTotal: 0,
            generalQueryParams: {
                pageNum: 1,
                pageSize: 10,
                tenantCode: "bjyq"
            },
            userInfoTemantCode: "", //获取用户信息的TemantCode
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                fondsName: [
                    { required: true, message: "请输入全宗名称", trigger: "blur" },
                ],
                fondsCode: [
                    { required: true, message: "请输入全宗号", trigger: "blur" }
                ]
            },
            //档案门类保存信息
            fondsCodecategoryData: [],
            // 获取row的key值
            getRowKeys(row) {
                return row.id;
            },

            // 要展开的行，数值的元素是row的key值
            expands: [],


        };
    },
    created() {

        //防止浏览器退回
        history.pushState(null, null, document.URL);
        window.addEventListener("popstate", function () {
            history.pushState(null, null, document.URL);
        });


        var sessionObj = JSON.parse(sessionStorage.getItem("sessionObj"))
        this.generalQueryParams.tenantCode = JSON.parse(sessionObj.data).tenantCode
        this.getGeneralList();
    },

    methods: {


        //隐藏展开箭头
        getRowClass(row) {
            console.log(row)
            if (row.row.children1111 === undefined) {
                return 'row-expand-cover';
            }
        },


        //解决vue+element— el-input 限制只能输入数字时和字母时与表单验证rules冲突问题
        salaryChange(e) {
            this.form.fondsCode = e.target.value;
        },

        /** 查询全宗列表 */
        getGeneralList() {
            this.loading = true;
            listFONDS(this.generalQueryParams).then(response => {
                if (this.active == "0") { //全宗时调用数据
                    this.generalList = response.rows;
                } else {

                    //档案门类时调用
                    if (sessionStorage.getItem("generalList")) { //如果已添加档案门类  缓存里会有sessionStorage.getItem("generalList")
                        //将获取到的分页数据和缓存数据合并，显示数据
                        const combined = response.rows.reduce((acc, cur) => {
                            const target = acc.find(e => e.id === cur.id);
                            if (target) {
                                Object.assign(target, cur);
                            } else {
                                acc.push(cur);
                            }
                            return acc;
                        }, JSON.parse(sessionStorage.getItem("generalList")));

                        //赛选合并好的分页数据渲染页面
                        var arrdata = [];
                        for (var i in response.rows) {
                            for (var k in combined) {
                                if (response.rows[i].id == combined[k].id) {
                                    // console.log(response.rows[i],)
                                    arrdata.push(combined[k])
                                }
                            }
                        }

                        this.generalList = arrdata;
                    } else {
                        this.generalList = response.rows;
                    }
                    //  this.generalList = sessionStorage.getItem("generalList") ? JSON.parse(sessionStorage.getItem("generalList")) : response.rows;
                }
                this.generalTotal = response.total;
                this.loading = false;
            }
            );
        },

        /**获取门类模板列表 */
        getcatemodelList() {
            this.loading = true;
            getcatemodeltreehadgroup().then(response => {
                // console.log(response.data)
                this.catemodelList = response.data;
                this.loading = false;
            }
            );
        },

        // 添加多选框选中数据
        selectionChange(selection) {
            // this.ids = selection.map(item => item.id);
            // this.single = selection.length !== 1
            // this.multiple = !selection.length
            var templateSelection = [];
            if (selection.length == 2) {
                this.$refs.multipleTable.clearSelection(); //清空列表的选中
                this.$refs.multipleTable.toggleRowSelection(selection[selection.length - 1]); //只显示选中最后一个 这时val还是多选的列表(就是你选中的几个数据)
            } else if (selection.length === 1) {
                this.templateSelection = selection[selection.length - 1];
            }
            else if (selection.length > 2) {
                this.$refs.multipleTable.clearSelection();

            } else {
                this.templateSelection = []; //this.multipleTable是选中行的最后一条数据
            }
            this.ids = this.templateSelection.id;

        },
        // 表单重置
        reset() {
            this.form = {
                fondsName: null,
                fondsCode: null,
            };
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.open = true;
            this.title = "添加立档单位全宗";
            this.reset();
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const ID = row.id || this.ids;
            getFONDS(ID).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改立档单位全宗";
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != undefined) {
                        updateFONDS(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getGeneralList();
                        });
                    } else {
                        addFONDS(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getGeneralList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ID = row.id || this.ids;
            this.$modal.confirm('是否确认删除全宗名称为"' + row.fondsName + '"的数据项？').then(function () {
                return delFONDS(ID);
            }).then(() => {
                this.getGeneralList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },

        //点击确定获取门类模板树节点集合
        getCheckedNodes() {
            this.expands = [];
            var nodes = this.$refs.tree.getCheckedNodes(true, true)
            //  this.generalList = sessionStorage.getItem("generalList") ? JSON.parse(sessionStorage.getItem("generalList")) :this.generalList;
            for (var i in this.generalList) {
                if (this.generalList[i].id == this.ids) {
                    this.generalList[i].children1111 = nodes
                }
            }
            this.openCatemodel = false;
            if (sessionStorage.getItem("generalList")) {
                let newDatas = [...this.generalList, ...JSON.parse(sessionStorage.getItem("generalList"))];

                let d = []
                let hash = {}
                d = newDatas.reduce((item, next) => {
                    console.log(next, hash[next.id], "dklsfjkl")
                    hash[next.id] ? '' : hash[next.id] = true && item.push(next)

                    return item
                }, [])
                console.log(d);

                sessionStorage.setItem("generalList", JSON.stringify(d))
            } else {
                sessionStorage.setItem("generalList", JSON.stringify(this.generalList))
            }


            this.getGeneralList();

            this.expands.push(this.ids)
            this.isExpands = true;

        },
        getCheckedNodesCancel() {
            this.openCatemodel = false;
        },
        //添加全宗门类模板
        addCatemodelTap() {

            // console.log(this.ids, "====")

            if (this.ids !== undefined) {
                this.openCatemodel = true;
                this.catemodelTitle = "添加全宗门类模板"
                this.getcatemodelList();
                var dataRow = this.generalList.filter((item) => {
                    return item.id == this.ids
                })
                //判断当前全宗里面是否又选择的门类  回显数据
                if (dataRow[0]?.children1111 && dataRow[0]?.children1111.length > 0) {
                    var arr = [];
                    for (var i in dataRow[0].children1111) {
                        arr.push(dataRow[0].children1111[i].id)
                    }
                    //  console.log(arr, "有children=====")
                    this.$nextTick(() => {
                        this.$refs.tree.setCheckedKeys(arr)
                    })
                } else {
                    // console.log(arr, "没有children=====")
                    this.$refs.tree?.setCheckedKeys([])
                }

            } else {
                this.$modal.msgError("请选择添加的全宗门类");
            }
        },

        //下一步
        prevTap() {
            if (this.active == 0) {
                if (this.generalList.length <= 0) {
                    this.$modal.msgError("请先添加全宗哦")
                } else {
                    this.isbutton = true;
                    this.generalQueryParams.pageNum = 1
                    this.generalQueryParams.pageSize = 10
                    this.getGeneralList();
                    if (this.active++ > 2) this.active = 0;
                }
            } else if (this.active == 1) {
                var dataArr = [];
                var sessionDatalist = JSON.parse(sessionStorage.getItem("generalList"))
                for (var i in sessionDatalist) {
                    //  console.log(sessionDatalist[i].children1111)
                    if (sessionDatalist[i].children1111 != undefined) {
                        var arr = [];
                        for (var j in sessionDatalist[i].children1111) {
                            arr.push(sessionDatalist[i].children1111[j].id)
                        }

                        dataArr.push({ "fondsCode": sessionDatalist[i].fondsCode, "category": arr })
                    } else {
                        // this.$modal.msgError("全宗号为" + sessionDatalist[i].fondsCode + "全宗未选择门类,请先选择门类！");
                        //     return false;
                    }

                }
                console.log(dataArr, "++++++++")
                if (dataArr.length <= 0) {
                    this.$modal.msgError("请先给全宗添加门类哦")
                } else {
                    //调用接口
                    mdataGroup(dataArr).then(res => {
                        if (res.code == 200) {
                            this.isbutton = false;
                            sessionStorage.removeItem("generalList");
                            if (this.active++ > 2) this.active = 1;
                            this.$router.push({ path: this.redirect || "/" }).catch(() => { });
                        }
                    })
                }
            }
        },
        //上一步
        nextTap() {
            if (this.active > 0) { this.active-- }
            sessionStorage.removeItem("generalList");
            this.generalQueryParams.pageNum = 1
            this.generalQueryParams.pageSize = 10
            this.getGeneralList();
            this.isbutton = false;
            this.expands = [];

        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.generalQueryParams.pageSize = val;
            this.getGeneralList();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.generalQueryParams.pageNum = val;
            this.getGeneralList();
        }
    },
    beforeDestroy() {
        sessionStorage.removeItem("generalList")
    }
}
</script>

<style lang="scss" scoped>
::v-deep .row-expand-cover td .el-table__expand-icon {
    visibility: hidden;
}

.init-container {
    padding-top: 30px;

    .finish-title {
        width: 50%;
        margin: 0px auto 30px;
    }

    .init-main {
        width: 60%;
        box-shadow: 0px 2px 15px 6px rgb(237, 236, 236);
        border-radius: 20px;
        margin: 0 auto;
        padding: 30px;
        height: 750px;
        overflow-y: hidden;
        position: relative;


        .main-iscrll {
            height: 600px;
            width: 100%;
            overflow-y: auto;
            overflow-x: hidden;
        }

        .el-page {
            right: 30px;
            position: absolute;
            white-space: nowrap;
            padding: 2px 5px;
            color: #303133;
            font-weight: bold;
            bottom: 30px
        }
    }
}

.el-button-xyb {
    display: flex;
    flex-direction: row;
    justify-content: center;
    margin: 30px auto 0;
    // display: block;
}
</style>
